package cn.wolfcode.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 李新雨的项目86176
 * @version 1.0
 * @date 2024-11-07 22:24
 */
public class CharsetFilter implements Filter {
    private String charset;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
           charset = filterConfig.getInitParameter("charset");
    }

    /**
     * todo 过滤器
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;
        if(charset!=null){
            httpServletRequest.setCharacterEncoding(charset);
            httpServletResponse.setCharacterEncoding(charset);
        }else {
            httpServletRequest.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {
//        Filter.super.destroy();
    }
}
